package com.zhu.pre.service.impl;

import com.sanploy.common.conf.PubliceVariable;
import com.sanploy.common.domain.User;
import com.sanploy.common.domain.vo.TokenVo;
import com.sanploy.common.enums.Meta;
import com.sanploy.common.vo.BaseException;
import com.sanploy.wechat.conf.Constant;
import com.sanploy.wechat.dto.WeChatLoginBack;
import com.sanploy.wechat.service.WechatSmallService;
import com.zhu.pre.mapper.MUserMapper;
import com.zhu.pre.service.MUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhu yingzhi on 2017/9/21.
 * @author yingzhi zhu
 * 手机用户逻辑处理接口实现
 */
@Service
public class MUserServiceImpl implements MUserService {

    @Autowired
    private MUserMapper userMapper;


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WechatSmallService wechatSmallService;

    @Override
    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }

    @Override
    public User findUserById(Long id) {
        return userMapper.findUserById(id);
    }

    @Override
    public User findUserByOpenId(String open_id) {
        return userMapper.findUserByOpenid(open_id);
    }

    @Override
    public int logout(String token) {
        redisTemplate.opsForValue().getOperations().delete(token);
        return PubliceVariable.SuccessfulInt;
    }

    @Override
    public int register(String token, User user) throws BaseException {
        System.out.println("register token:"+token);
        ValueOperations operations = redisTemplate.opsForValue();
        user.registUser(Optional.ofNullable((User)operations.get(token)).orElseThrow(()->new BaseException(Meta.NullFail)));
        if (userMapper.insertUser(user)< PubliceVariable.MinEffectRow){
            throw new BaseException(Meta.UpdateFail);
        }
        redisTemplate.opsForValue().set(token,user,Constant.SessionTime, TimeUnit.SECONDS);
        return PubliceVariable.SuccessfulInt;
    }


    @Override
    public TokenVo login(String code, String token) throws IOException, BaseException {

        TokenVo tokenVo = new TokenVo();
        System.out.println("token:"+token);
        //判断是否有此token的缓存 有则返回 无则通过code认证
        if (!"".equals(token) && redisTemplate.opsForValue().get(token)!=null){
            tokenVo.setIs_register(true);
            tokenVo.setToken(token);
            return tokenVo;
        }
        Long oldTime = System.currentTimeMillis();
        //线上接口
//        WeChatLoginBack weChatLoginBack = wechatSmallService.login(code);
//        System.out.println("微信登录接口请求耗时："+(System.currentTimeMillis()-oldTime));
        WeChatLoginBack weChatLoginBack = returnWechar();
        System.out.println("oppenid:"+weChatLoginBack.getOpenid());

        String sessionKey = UUID.randomUUID().toString();
        //TODO 如果没有用户会多一次redis存储 修改他
        User user = Optional.ofNullable(userMapper.findUserByOpenid(weChatLoginBack.getOpenid())).
                orElseGet(()-> new User(weChatLoginBack.getOpenid(),weChatLoginBack.getSession_key()));

        redisTemplate.opsForValue().set(sessionKey,user,Constant.SessionTime, TimeUnit.SECONDS);


        tokenVo.setToken(sessionKey);
        if (userMapper.findUserByOpenid(weChatLoginBack.getOpenid())!=null){
            tokenVo.setIs_register(true);
        }
        System.out.println("getSession_key:"+weChatLoginBack.getSession_key());
        return tokenVo;
    }

    public WeChatLoginBack returnWechar(){
        WeChatLoginBack w = new WeChatLoginBack();
        w.setOpenid("oe7QQ0ewebsgVSGkEGfICtKunhL8");
        w.setSession_key("WMU\\/1sZRjT7iZk1NxKIpuA==");
        return w;
    }
}
